package com.easy.service.impl;

import com.easy.bean.Room;
import com.easy.mapper.RoomDao;
import com.easy.service.RoomService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    RoomDao roomDao;
    //新增数据
    @Override
    public Room add(Room room) {
        // 直接设置一个最可能被接受的status值
        room.setStatus("0");
        
        // 为room_number字段设置值（使用随机数）
        if (room.getRoom_number() == null || room.getRoom_number().trim().isEmpty()) {
            // 生成一个随机房间号
            String roomNumber = String.valueOf((int) (Math.random() * 10000) + 1000);
            room.setRoom_number(roomNumber);
        }
        
        // 确保electronics和floor字段也不为空
        if (room.getElectronics() == null) {
            room.setElectronics("");
        }
        if (room.getFloor() == null) {
            room.setFloor("");
        }
        
        roomDao.add(room);
        //通过主键查询数据库中的数据
        try {
            Room result=roomDao.one(Integer.valueOf(room.getRoom_number()));
            return result;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public int del(String room_number) {
        // 检查房间号是否为null或"undefined"
        if (room_number == null || "undefined".equals(room_number)) {
            return 0; // 或者抛出自定义异常
        }
        try {
            return roomDao.del(Integer.valueOf(room_number));
        } catch (NumberFormatException e) {
            // 处理无效的房间号
            return 0; // 或者抛出自定义异常
        }
    }

    @Override
    public Room edit(Room room) {
        // 在编辑时，如果status字段不为空，则尝试设置一个安全的值
        if (room.getStatus() != null && !room.getStatus().trim().isEmpty()) {
            room.setStatus("0");
        }
        
        roomDao.edit(room);
        try {
            Room result=roomDao.one(Integer.valueOf(room.getRoom_number()));
            return result;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public List<Room> all(Room room) {
        return roomDao.all(room);
    }

    @Override
    public Room one(String room_number) {
        // 检查房间号是否为null或"undefined"
        if (room_number == null || "undefined".equals(room_number)) {
            return null; // 或者抛出自定义异常
        }
        try {
            return roomDao.one(Integer.valueOf(room_number));
        } catch (NumberFormatException e) {
            // 处理无效的房间号
            return null; // 或者抛出自定义异常
        }
    }

    @Override
    public void page(Page page, Room room) {
        int count = roomDao.pageCount(room);
        Object data=roomDao.page(page, room);
        page.setCount(count);
        page.setData(data);
    }
}